package com.ti.demo.autoconfigure;

import jakarta.servlet.Filter;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.zalando.logbook.Logbook;

import java.nio.charset.StandardCharsets;

import static org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type.SERVLET;

/**
 * @description: com.ti.demo.autoconfigure
 * @Author Triagen
 * @Date 2025/7/28 16:56
 */
@ConditionalOnWebApplication(type = SERVLET)
@ConditionalOnClass(Logbook.class)
@AutoConfiguration
public class LogServletAutoConfiguration {
    /**
     * logbook响应体默认使用ISO_8859_1编码，为避免中文打印乱码，增加此filter
     */
    @Bean("utf8Filter")
    public FilterRegistrationBean utf8Filter() {
        Filter utf8Filter = (request, response, chain) -> {
            response.setCharacterEncoding(StandardCharsets.UTF_8.name());
            chain.doFilter(request, response);
        };
        FilterRegistrationBean utf8Registration = new FilterRegistrationBean(utf8Filter);
        utf8Registration.setName("utf8Filter");
        return utf8Registration;
    }
}
